﻿using System.Web.Mvc;
using ShoppingCart.Domain.Entities;
using System.Linq;
using System.Web;
using ShoppingCart.Business.Concrete;
using ShoppingCart.Business.Abstract;
using Ninject;

namespace ShoppingCart.WebUI.Controllers {

    //[Authorize]
    public class AdminController : Controller {
        [Inject]
        public IProductService productService { get; set; }

        public ViewResult Index() {
            return View(productService.Products);
        }

        public ViewResult Create() {
            return View("Edit", new Product());
        }

        public ViewResult Edit(int productId) {
            Product product = productService.Products.FirstOrDefault(p => p.ProductID == productId);
            return View(product);
        }

        [HttpPost]
        public ActionResult Delete(int productId) {
            Product prod = productService.Products.FirstOrDefault(p => p.ProductID == productId);
            if (prod != null) {
                productService.DeleteProduct(prod);
                TempData["message"] = string.Format("{0} was deleted", prod.Name);
            } 
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Edit(Product product) {

            if (ModelState.IsValid) {
                // save the product
                productService.SaveProduct(product);
                // add a message to the viewbag
                TempData["message"] = string.Format("{0} has been saved", product.Name);
                // return the user to the list
                return RedirectToAction("Index");
            } else {
                // there is something wrong with the data values
                return View(product);
            }
        }
    }
}
